import axios from "axios";
// import qs from 'qs'
import router from "@/router/index";
import useUserStore from "@/store/modules/user";
import errorCode from "@/utils/errorCode";
import storage from "@/utils/storage";
import { TOKEN } from "@/store/mutation-types";

const toLogin = () => {
  useUserStore()
    .logout()
    .then(() => {
      router.push({
        name: "login",
        query: {
          redirect:
            router.currentRoute.value.path !== "/login"
              ? router.currentRoute.value.fullPath
              : undefined
        }
      });
    });
};

const request = axios.create({
  baseURL:
    import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === "true"
      ? "/proxy/"
      : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 20000,
  responseType: "json"
});

// 异常拦截处理器
const errorHandler = (error) => {
  console.log("err" + error);
  let { message } = error;
  if (message === "Network Error") {
    message = "后端接口连接异常";
  } else if (message.includes("timeout")) {
    message = "系统接口请求超时";
  } else if (message.includes("Request failed with status code")) {
    message = "系统接口" + message.substr(message.length - 3) + "异常";
  }
  ElNotification.error({
    message: message,
    duration: 5000
  });
  //  return Promise.reject(error) //注释该行，否则接口请求失败会一直请求刷新错误数据，这里保证请求一次
};
request.interceptors.request.use((config) => {
  const token = storage.local.get(TOKEN);
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers["Authorization"] = "Bearer " + token; // 让每个请求携带自定义token 请根据实际情况自行修改
    // config.headers['accessAccess-Token'] = token
  }
  // get请求映射params参数
  if (config.method === "get" && config.params) {
    let url = config.url + "?";
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      // 修改漏洞
      if (value != null && typeof value !== "undefined") {
        if (typeof value === "object") {
          for (const key of Object.keys(value)) {
            const params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config;
}, errorHandler);

// response interceptor
request.interceptors.response.use((res) => {
  // 请求rul
  const requestUrl = res.config.url;
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200;
  // 获取错误信息
  const msg = errorCode[code] || res.data.msg || errorCode["default"];
  if (code === 401) {
    ElNotification({
      type: "error",
      title: "温馨提示",
      dangerouslyUseHTMLString: true,
      message: `登陆状态过期，请重新登陆！`,
      position: "top-right",
      duration: 5000
    });
    toLogin();
  } else if (code === 500) {
    console.log(requestUrl);
    // if (ElNotification !== "/login") {
    ElNotification.error({
      message: msg,
      description: msg
    });
    // }
  } else if (code !== 200) {
    ElNotification({
      type: "error",
      title: "提示",
      message: msg,
      position: "top-right",
      duration: 2000
    });
  } // else {
  //   toLogin();
  // }
  return res.data;

  // return Promise.reject(msg);
}, errorHandler);

export default request;
